//
//  HomeVM.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/3.
//

import RxSwift
import Combine
import ToastUI
import SwiftUI
import UTEBluetoothRYApi

class HomeVM: ObservableObject {
    @Published var showOnboarding: Bool = false
    @Published var currentWatch: String = "手表名称"
    @Published var steps: Int = 100
    @Published var targetSteps: Int = 600
    
    @Published var ka: Int = 10
    @Published var targetKa: Int = 400
    
    @Published var distance: Int = 1
    @Published var targetDistance: Int = 30
    
    @Published var currentTime: String = "7月12日 10:00"
    @Published var heartRate: Int = 98
    
    @Published var deviceList: [DeviceInfo] = []
    
    init() {
        UTEBluetoothMgr.sharedInstance().initUTEMgr()
        deviceList = DeviceManager.shared.devices
        showOnboarding = UserDefaults.standard.bool(forKey: disShowOnboarding) == false ? true : false
        NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceConnected), name: NSNotification.Name("BLEDeviceConnected"), object: nil)
    }
    
    @objc private func handleDeviceConnected() {
        getCurrentDayTotalWorkoutData()
    }
    
    func getCurrentDayTotalWorkoutData() {
         AppState.shared.bleManager.mgrDevice.getCurrentDayTotalWorkoutData { [weak self] model, errorCode, uteDict in
            guard let self = self else { return }
            if errorCode == 100000 {
                
                DispatchQueue.main.async {
                    var kcal: Int = 0
                    var step: Int = 0
                    var distance: Int = 0
                    if let lastHeartRate: UTEModelTodayHRM = model?.lastHeartRate {
                        self.heartRate = lastHeartRate.rate
                    } else {
                        self.heartRate = 0
                    }
                    if let motionData = model?.motionData {
                        motionData.forEach { data in
                            step = step + (data as! UTEModelTodayDetail).step
                            kcal = kcal + (data as! UTEModelTodayDetail).kcal
                            distance = distance + (data as! UTEModelTodayDetail).distance
                        }
                        self.steps = step
                        self.ka = kcal
                        self.distance = distance
                        print("=====", motionData)
                    }
                }
            } else {
                print("获取当前天运动数据失败，错误码：\(errorCode)")
            }
            
            
        }
    }
    
    
}
